package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.List;

/**
 * <p>
 * 员工信息 前端控制器
 * </p>
 *
 * @author 宋
 * @since 2022-06-06
 */

@Slf4j
@RestController
@RequestMapping("/employee")

public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    //登录业务
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //1.拿到前端传来的数据 判断(dm5加密)用户密码,用户名是否正确
        String password = employee.getPassword();    //正常用户的密码
        password = DigestUtils.md5DigestAsHex(password.getBytes());    //md5转密

        //查询包装器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //查询语句 条件是Username是否匹配
        LambdaQueryWrapper<Employee> eq = queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee eml = employeeService.getOne(eq);    //把eq语句传进去执行对应的sql   得到查询的结果

        // 2 . 用返回的对象里的数据和用户输入的数据进行判断
        // 2.1 判断账号是否存在
        if (eml == null) {
            return R.error("账号错误");
        }
        // 2.2 判断密码是否正确
        if (!eml.getPassword().equals(password)) {
            return R.error("密码错误");
        }



        // 2.2 判断账号是否被禁用 1正常 2禁用
        if (eml.getStatus() == 0) {
            return R.error("账号被禁用");
        }
        log.info("账号登录成功了");
        // 3 . 走到这说明登录成功了 把数据存到Session里, 需要 request  参数里要加上
        HttpSession session = request.getSession();
        session.setAttribute("employee", eml.getId());   //把id存到session里 后面会调用
        session.setAttribute("employeeData", eml);
        return R.success(eml);
    }

    //退出业务
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清除session里的id信息
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    //添加新员工
    @PostMapping
    public R<String> add(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("前端传过来的 {}", employee);
       /*
        idNumber: "111222333444555666"
        name: "张三"
        phone: "15931376677"
        sex: "1"
        username: "zhangsan"*/
        // 1 . 设置初始化密码 ,创建时间create_time ,更新时间update_time ,创建人create_user ,修改人update_user
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
  /*      employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser((Long) request.getSession().getAttribute("employee"));
        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));*/

        // 2 . 执行sql语句,添加到数据库
        log.info("最终要添加的 {}", employee);
        employeeService.save(employee);

        return R.success("添加成功");
    }

    //分页查询
    //Request URL: http://127.0.0.1:8080/employee/page?page=1&pageSize=2
    //Request Method: GET
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        log.info("前端传过来的 page={},pageSize={},name={}", page, pageSize, name);

        //  1. 分页构造器--分页规则    0 , 2
        Page pageinfo = new Page(page, pageSize);
        //  2 .条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //  查询条件--name进行模糊查询  判断有没有传name名字进来
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getUsername, name);
        //  查询后的排序--更新时间倒序排序
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //代理对象执行查询
        Page page1 = employeeService.page(pageinfo, queryWrapper);
        List records = page1.getRecords();
        System.out.println(records);
        log.info("查询结果 {}", records);

        return R.success(page1);
    }


    //
    //Request URL: http://127.0.0.1:8080/employee
    //Request Method: PUT
    //{id: 1534529152904986600, status: 0}
    @PutMapping
    public R<String> update(HttpSession session, @RequestBody Employee employee) {
//        Long empId = (Long) session.getAttribute("employee");
//        employee.setUpdateUser(empId);                //更新人
//        employee.setUpdateTime(LocalDateTime.now());  //更新时间
        log.info("要更新的数据 {}", employee);
        //空字段不会更新,只会更新被赋值的字段
        employeeService.updateById(employee);
        return R.success("设置成功");
    }

    //根据id查询
    //Request URL: http://127.0.0.1:8080/employee/1534529152904986625
    //Request Method: GET
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("前端传来的di={}",id);
        Employee byId = employeeService.getById(id);
        return R.success(byId);
    }
}

